<template>
  <div class="realtime">
    <!-- 实时数据仪表盘 -->
    <el-row :gutter="20" class="gauge-section">
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="gauge-card" shadow="hover">
          <template #header>
            <div class="gauge-header">
              <span>温度</span>
              <el-tag :type="getTemperatureStatus(latestData.temperature).type" size="small">
                {{ getTemperatureStatus(latestData.temperature).text }}
              </el-tag>
            </div>
          </template>
          <div class="gauge-container">
            <v-chart 
              :option="temperatureGaugeOption" 
              :loading="loading"
              autoresize
            />
          </div>
          <div class="gauge-info">
            <div class="current-value">{{ latestData.temperature || '--' }}°C</div>
            <div class="update-time">{{ formatUpdateTime(latestData.createdAt) }}</div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="gauge-card" shadow="hover">
          <template #header>
            <div class="gauge-header">
              <span>湿度</span>
              <el-tag :type="getHumidityStatus(latestData.humidity).type" size="small">
                {{ getHumidityStatus(latestData.humidity).text }}
              </el-tag>
            </div>
          </template>
          <div class="gauge-container">
            <v-chart 
              :option="humidityGaugeOption" 
              :loading="loading"
              autoresize
            />
          </div>
          <div class="gauge-info">
            <div class="current-value">{{ latestData.humidity || '--' }}%</div>
            <div class="update-time">{{ formatUpdateTime(latestData.createdAt) }}</div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="gauge-card" shadow="hover">
          <template #header>
            <div class="gauge-header">
              <span>气压</span>
              <el-tag :type="getPressureStatus(latestData.pressure).type" size="small">
                {{ getPressureStatus(latestData.pressure).text }}
              </el-tag>
            </div>
          </template>
          <div class="gauge-container">
            <v-chart 
              :option="pressureGaugeOption" 
              :loading="loading"
              autoresize
            />
          </div>
          <div class="gauge-info">
            <div class="current-value">{{ formatPressure(latestData.pressure) }}</div>
            <div class="update-time">{{ formatUpdateTime(latestData.createdAt) }}</div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="gauge-card" shadow="hover">
          <template #header>
            <div class="gauge-header">
              <span>光照强度</span>
              <el-tag :type="getLightStatus(latestData.lightIntensity).type" size="small">
                {{ getLightStatus(latestData.lightIntensity).text }}
              </el-tag>
            </div>
          </template>
          <div class="gauge-container">
            <v-chart 
              :option="lightGaugeOption" 
              :loading="loading"
              autoresize
            />
          </div>
          <div class="gauge-info">
            <div class="current-value">{{ latestData.lightIntensity || '--' }} lux</div>
            <div class="update-time">{{ formatUpdateTime(latestData.createdAt) }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时趋势图 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>实时数据趋势</span>
              <div class="header-actions">
                <el-radio-group v-model="chartTimeRange" size="small">
                  <el-radio-button label="1">1小时</el-radio-button>
                  <el-radio-button label="6">6小时</el-radio-button>
                  <el-radio-button label="12">12小时</el-radio-button>
                  <el-radio-button label="24">24小时</el-radio-button>
                </el-radio-group>
                <el-button-group style="margin-left: 10px">
                  <el-button size="small" @click="toggleChartType">
                    <el-icon><TrendCharts /></el-icon>
                    {{ chartType === 'line' ? '切换柱状图' : '切换折线图' }}
                  </el-button>
                  <el-button size="small" @click="exportChartData">
                    <el-icon><Download /></el-icon>
                    导出
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>
          <div class="chart-container">
            <v-chart 
              ref="realtimeChart" 
              :option="realtimeChartOption" 
              :loading="chartLoading"
              autoresize
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-row :gutter="20" class="table-section">
      <el-col :span="24">
        <el-card class="table-card" shadow="hover">
          <template #header>
            <div class="table-header">
              <span>最新数据记录</span>
              <div class="header-actions">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索数据..."
                  size="small"
                  style="width: 200px"
                  clearable
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-button size="small" @click="refreshTableData">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </div>
          </template>
          <el-table 
            :data="filteredTableData" 
            :loading="tableLoading"
            stripe
            border
            height="400"
            @sort-change="handleSortChange"
          >
            <el-table-column prop="id" label="ID" width="80" sortable />
            <el-table-column prop="temperature" label="温度(°C)" width="120" sortable>
              <template #default="{ row }">
                <span :style="{ color: getTemperatureColor(row.temperature) }">
                  {{ numberUtils.format(row.temperature, 1) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="humidity" label="湿度(%)" width="120" sortable>
              <template #default="{ row }">
                <span :style="{ color: getHumidityColor(row.humidity) }">
                  {{ numberUtils.format(row.humidity, 1) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="pressure" label="气压(hPa)" width="140" sortable>
              <template #default="{ row }">
                <span :style="{ color: getPressureColor(row.pressure) }">
                  {{ numberUtils.format(row.pressure / 100, 0) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="lightIntensity" label="光照强度(lux)" width="140" sortable>
              <template #default="{ row }">
                <span :style="{ color: getLightColor(row.lightIntensity) }">
                  {{ row.lightIntensity }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="记录时间" min-width="180" sortable>
              <template #default="{ row }">
                {{ timeUtils.format(row.createdAt) }}
              </template>
            </el-table-column>
            <el-table-column label="数据质量" width="100">
              <template #default="{ row }">
                <el-tag :type="getDataQualityType(row)" size="small">
                  {{ getDataQualityText(row) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button size="small" type="text" @click="viewDataDetail(row)">
                  详情
                </el-button>
                <el-button size="small" type="text" @click="analyzeData(row)">
                  分析
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="table-pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="totalCount"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="数据详情"
      width="600px"
      :before-close="handleDetailClose"
    >
      <div class="detail-content" v-if="selectedData">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="数据ID">{{ selectedData.id }}</el-descriptions-item>
          <el-descriptions-item label="记录时间">{{ timeUtils.format(selectedData.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="温度">{{ selectedData.temperature }}°C</el-descriptions-item>
          <el-descriptions-item label="湿度">{{ selectedData.humidity }}%</el-descriptions-item>
          <el-descriptions-item label="气压">{{ selectedData.pressure }} Pa</el-descriptions-item>
          <el-descriptions-item label="光照强度">{{ selectedData.lightIntensity }} lux</el-descriptions-item>
          <el-descriptions-item label="数据质量" :span="2">
            <el-tag :type="getDataQualityType(selectedData)">
              {{ getDataQualityText(selectedData) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-charts" style="margin-top: 20px">
          <h4>数据可视化</h4>
          <div class="mini-charts">
            <div class="mini-chart">
              <v-chart :option="getMiniChartOption('temperature', selectedData.temperature, '°C')" />
            </div>
            <div class="mini-chart">
              <v-chart :option="getMiniChartOption('humidity', selectedData.humidity, '%')" />
            </div>
            <div class="mini-chart">
              <v-chart :option="getMiniChartOption('pressure', selectedData.pressure / 100, 'hPa')" />
            </div>
            <div class="mini-chart">
              <v-chart :option="getMiniChartOption('light', selectedData.lightIntensity, 'lux')" />
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="exportSelectedData">导出数据</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 连接状态指示器 -->
    <div class="connection-status" :class="connectionStatus.class">
      <el-icon><component :is="connectionStatus.icon" /></el-icon>
      <span>{{ connectionStatus.text }}</span>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh, TrendCharts, Download, Search,
  Connection, CircleClose as DisconnectIcon,
  Warning
} from '@element-plus/icons-vue'
import VChart from 'vue-echarts'
import { useSensorStore } from '@/stores/sensor'
import { timeUtils, numberUtils, colorUtils } from '@/utils'
import { sensorChartConfigs, createGaugeChartOption } from '@/utils/charts'
import {
  Monitor,
  Sunny,
  Cloudy,
  Compass
} from '@element-plus/icons-vue'

// 存储
const sensorStore = useSensorStore()

// 响应式数据
const loading = ref(false)
const chartLoading = ref(false)
const tableLoading = ref(false)
const autoRefresh = ref(true)
const refreshInterval = ref(3) // 默认3秒刷新一次
const chartTimeRange = ref('6')
const chartType = ref('line')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const totalCount = ref(0)
const detailDialogVisible = ref(false)
const selectedData = ref(null)
const refreshTimer = ref(null)
const connectionTimer = ref(null)
const realtimeChart = ref(null)
const connected = ref(true) // 添加连接状态变量

// 连接状态
const connectionStatus = computed(() => {
  if (connected.value) {
    return {
      class: 'connected',
      icon: 'Connection',
      text: '已连接'
    }
  } else {
    return {
      class: 'disconnected',
      icon: 'DisconnectIcon',
      text: '未连接'
    }
  }
})

// 计算属性
const latestData = computed(() => sensorStore.latestData || {})

const filteredTableData = computed(() => {
  let data = sensorStore.recentData || []
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    data = data.filter(item => 
      item.id.toString().includes(keyword) ||
      item.temperature.toString().includes(keyword) ||
      item.humidity.toString().includes(keyword) ||
      timeUtils.format(item.createdAt).toLowerCase().includes(keyword)
    )
  }
  totalCount.value = data.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return data.slice(start, end)
})

// 仪表盘配置
const temperatureGaugeOption = computed(() => {
  return createGaugeChartOption({
    title: '',
    value: latestData.value.temperature || 0,
    min: -20,
    max: 50,
    unit: '°C',
    thresholds: [
      { min: -20, max: 0, color: '#1890ff' },
      { min: 0, max: 25, color: '#52c41a' },
      { min: 25, max: 35, color: '#faad14' },
      { min: 35, max: 50, color: '#f5222d' }
    ]
  })
})

const humidityGaugeOption = computed(() => {
  return createGaugeChartOption({
    title: '',
    value: latestData.value.humidity || 0,
    min: 0,
    max: 100,
    unit: '%',
    thresholds: [
      { min: 0, max: 30, color: '#fa8c16' },
      { min: 30, max: 60, color: '#52c41a' },
      { min: 60, max: 80, color: '#1890ff' },
      { min: 80, max: 100, color: '#722ed1' }
    ]
  })
})

const pressureGaugeOption = computed(() => {
  return createGaugeChartOption({
    title: '',
    value: (latestData.value.pressure || 0) / 100,
    min: 900,
    max: 1100,
    unit: 'hPa',
    thresholds: [
      { min: 900, max: 950, color: '#f5222d' },
      { min: 950, max: 1000, color: '#fa8c16' },
      { min: 1000, max: 1030, color: '#52c41a' },
      { min: 1030, max: 1060, color: '#1890ff' },
      { min: 1060, max: 1100, color: '#722ed1' }
    ]
  })
})

const lightGaugeOption = computed(() => {
  return createGaugeChartOption({
    title: '',
    value: latestData.value.lightIntensity || 0,
    min: 0,
    max: 2000,
    unit: 'lux',
    thresholds: [
      { min: 0, max: 50, color: '#434343' },
      { min: 50, max: 200, color: '#722ed1' },
      { min: 200, max: 500, color: '#1890ff' },
      { min: 500, max: 1000, color: '#52c41a' },
      { min: 1000, max: 2000, color: '#faad14' }
    ]
  })
})

// 实时图表配置
const realtimeChartOption = computed(() => {
  const data = sensorStore.historicalData || []
  if (data.length === 0) {
    return {
      title: {
        text: '暂无数据',
        left: 'center',
        top: 'center',
        textStyle: { color: '#999', fontSize: 16 }
      }
    }
  }
  
  if (chartType.value === 'line') {
    return sensorChartConfigs.combined(data)
  } else {
    // 柱状图配置
    return {
      title: {
        text: '传感器数据柱状图',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['温度', '湿度', '光照强度'],
        top: 30
      },
      xAxis: {
        type: 'category',
        data: data.map(item => timeUtils.format(item.createdAt, 'HH:mm'))
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '温度',
          type: 'bar',
          data: data.map(item => item.temperature),
          itemStyle: { color: '#f5222d' }
        },
        {
          name: '湿度',
          type: 'bar',
          data: data.map(item => item.humidity),
          itemStyle: { color: '#1890ff' }
        },
        {
          name: '光照强度',
          type: 'bar',
          data: data.map(item => item.lightIntensity / 10), // 缩放以便显示
          itemStyle: { color: '#faad14' }
        }
      ]
    }
  }
})

// 方法
const formatPressure = (pressure) => {
  if (!pressure) return '--'
  return `${numberUtils.format(pressure / 100, 0)} hPa`
}

const formatUpdateTime = (time) => {
  if (!time) return '--'
  return timeUtils.fromNow(time)
}

const getTemperatureStatus = (temp) => {
  if (!temp) return { type: 'info', text: '无数据' }
  if (temp < 0) return { type: 'primary', text: '极冷' }
  if (temp < 10) return { type: 'success', text: '冷' }
  if (temp < 25) return { type: 'success', text: '适中' }
  if (temp < 35) return { type: 'warning', text: '热' }
  return { type: 'danger', text: '极热' }
}

const getHumidityStatus = (humidity) => {
  if (!humidity) return { type: 'info', text: '无数据' }
  if (humidity < 30) return { type: 'warning', text: '干燥' }
  if (humidity < 60) return { type: 'success', text: '适中' }
  if (humidity < 80) return { type: 'primary', text: '湿润' }
  return { type: 'danger', text: '潮湿' }
}

const getPressureStatus = (pressure) => {
  if (!pressure) return { type: 'info', text: '无数据' }
  const hpa = pressure / 100
  if (hpa < 950) return { type: 'danger', text: '低压' }
  if (hpa < 1000) return { type: 'warning', text: '较低' }
  if (hpa < 1030) return { type: 'success', text: '正常' }
  if (hpa < 1060) return { type: 'primary', text: '较高' }
  return { type: 'danger', text: '高压' }
}

const getLightStatus = (light) => {
  if (!light) return { type: 'info', text: '无数据' }
  if (light < 50) return { type: 'danger', text: '黑暗' }
  if (light < 200) return { type: 'warning', text: '昏暗' }
  if (light < 500) return { type: 'primary', text: '室内' }
  if (light < 1000) return { type: 'success', text: '明亮' }
  return { type: 'warning', text: '强光' }
}

const getTemperatureColor = (temp) => colorUtils.getTemperatureColor(temp)
const getHumidityColor = (humidity) => colorUtils.getHumidityColor(humidity)
const getPressureColor = (pressure) => colorUtils.getPressureColor(pressure)
const getLightColor = (light) => colorUtils.getLightColor(light)

const getDataQualityType = (data) => {
  // 简单的数据质量检查
  const hasAllData = data.temperature && data.humidity && data.pressure && data.lightIntensity
  if (!hasAllData) return 'danger'
  
  const isReasonable = 
    data.temperature >= -50 && data.temperature <= 80 &&
    data.humidity >= 0 && data.humidity <= 100 &&
    data.pressure >= 80000 && data.pressure <= 120000 &&
    data.lightIntensity >= 0 && data.lightIntensity <= 2000
  
  return isReasonable ? 'success' : 'warning'
}

const getDataQualityText = (data) => {
  const type = getDataQualityType(data)
  const textMap = {
    success: '良好',
    warning: '异常',
    danger: '缺失'
  }
  return textMap[type] || '未知'
}

const getMiniChartOption = (type, value, unit) => {
  const colors = {
    temperature: '#f5222d',
    humidity: '#1890ff',
    pressure: '#52c41a',
    light: '#faad14'
  }
  
  return {
    series: [{
      type: 'gauge',
      radius: '80%',
      min: 0,
      max: type === 'temperature' ? 50 : type === 'humidity' ? 100 : type === 'pressure' ? 1100 : 2000,
      axisLine: {
        lineStyle: {
          width: 6,
          color: [[1, colors[type]]]
        }
      },
      pointer: {
        itemStyle: {
          color: colors[type]
        }
      },
      detail: {
        valueAnimation: true,
        formatter: `{value}${unit}`,
        color: colors[type],
        fontSize: 14
      },
      data: [{ value, name: type }]
    }]
  }
}

const refreshData = async () => {
  loading.value = true
  try {
    await Promise.all([
      sensorStore.fetchLatestData(),
      sensorStore.fetchHistoricalData(parseInt(chartTimeRange.value)),
      sensorStore.fetchRecentData(100)
    ])
    updateConnectionStatus('connected')
    connected.value = true
  } catch (error) {
    ElMessage.error('刷新数据失败')
    updateConnectionStatus('error')
    connected.value = false
  } finally {
    loading.value = false
  }
}

const refreshTableData = async () => {
  tableLoading.value = true
  try {
    await sensorStore.fetchRecentData(100)
  } catch (error) {
    ElMessage.error('刷新表格数据失败')
  } finally {
    tableLoading.value = false
  }
}

const toggleAutoRefresh = (enabled) => {
  autoRefresh.value = enabled
  if (enabled) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
}

const startAutoRefresh = () => {
  stopAutoRefresh()
  refreshTimer.value = setInterval(() => {
    refreshData()
  }, refreshInterval.value * 1000)
}

const stopAutoRefresh = () => {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value)
    refreshTimer.value = null
  }
}

const updateConnectionStatus = (status) => {
  const statusMap = {
    connected: {
      class: 'connected',
      icon: 'Connection',
      text: '连接正常'
    },
    disconnected: {
      class: 'disconnected',
      icon: 'DisconnectIcon',
      text: '连接断开'
    },
    error: {
      class: 'error',
      icon: 'Warning',
      text: '连接异常'
    }
  }
  
  Object.assign(connectionStatus, statusMap[status] || statusMap.error)
}

const toggleChartType = () => {
  chartType.value = chartType.value === 'line' ? 'bar' : 'line'
}

const exportChartData = () => {
  const data = sensorStore.historicalData || []
  if (data.length === 0) {
    ElMessage.warning('暂无数据可导出')
    return
  }
  
  const csvContent = [
    ['时间', '温度(°C)', '湿度(%)', '气压(Pa)', '光照强度(lux)'],
    ...data.map(item => [
      timeUtils.format(item.createdAt),
      item.temperature,
      item.humidity,
      item.pressure,
      item.lightIntensity
    ])
  ].map(row => row.join(',')).join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `sensor_data_${timeUtils.format(new Date(), 'YYYY-MM-DD_HH-mm-ss')}.csv`
  link.click()
  
  ElMessage.success('数据导出成功')
}

const handleSortChange = ({ column, prop, order }) => {
  // 这里可以实现排序逻辑
  console.log('排序变化:', { column, prop, order })
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const viewDataDetail = (data) => {
  selectedData.value = data
  detailDialogVisible.value = true
}

const analyzeData = async (data) => {
  try {
    // 这里可以实现单条数据的分析逻辑
    ElMessage.info('数据分析功能开发中...')
  } catch (error) {
    ElMessage.error('数据分析失败')
  }
}

const handleDetailClose = () => {
  detailDialogVisible.value = false
  selectedData.value = null
}

const exportSelectedData = () => {
  if (!selectedData.value) return
  
  const data = selectedData.value
  const csvContent = [
    ['字段', '值'],
    ['ID', data.id],
    ['温度(°C)', data.temperature],
    ['湿度(%)', data.humidity],
    ['气压(Pa)', data.pressure],
    ['光照强度(lux)', data.lightIntensity],
    ['记录时间', timeUtils.format(data.createdAt)]
  ].map(row => row.join(',')).join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `sensor_data_${data.id}.csv`
  link.click()
  
  ElMessage.success('数据导出成功')
}

// 监听器
watch(chartTimeRange, async () => {
  chartLoading.value = true
  try {
    await sensorStore.fetchHistoricalData(parseInt(chartTimeRange.value))
  } catch (error) {
    ElMessage.error('更新图表数据失败')
  } finally {
    chartLoading.value = false
  }
})

watch(refreshInterval, () => {
  if (autoRefresh.value) {
    startAutoRefresh()
  }
})

// 生命周期
onMounted(async () => {
  try {
    await refreshData()
    if (autoRefresh.value) {
      startAutoRefresh()
    }
    
    // 启动连接状态检查
    connectionTimer.value = setInterval(() => {
      // 实际连接状态检查
      if (sensorStore.latestData) {
        const lastUpdateTime = new Date(sensorStore.latestData.updatedAt || sensorStore.latestData.createdAt)
        const now = new Date()
        const diff = now - lastUpdateTime
        // 如果最后更新时间超过10秒，认为连接异常
        connected.value = diff < 10000
        updateConnectionStatus(connected.value ? 'connected' : 'error')
      }
    }, 5000)
    
    // 开始实时数据更新
    const stopRealTimeUpdate = sensorStore.startRealTimeUpdate(refreshInterval.value * 1000)
    
    // 组件卸载时停止更新
    onUnmounted(() => {
      stopRealTimeUpdate()
    })
  } catch (error) {
    ElMessage.error('初始化失败')
  }
})

onUnmounted(() => {
  stopAutoRefresh()
  if (connectionTimer.value) {
    clearInterval(connectionTimer.value)
  }
})
</script>

<style scoped>
.realtime {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
  position: relative;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.page-header p {
  font-size: 16px;
  color: #606266;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

/* 仪表盘样式 */
.gauge-section {
  margin-bottom: 20px;
}

.gauge-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.gauge-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.gauge-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.gauge-container {
  height: 200px;
  margin: 10px 0;
}

.gauge-info {
  text-align: center;
  padding: 10px;
  border-top: 1px solid #f0f0f0;
}

.current-value {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.update-time {
  font-size: 12px;
  color: #909399;
}

/* 图表样式 */
.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  border: none;
  border-radius: 12px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  flex-wrap: wrap;
  gap: 10px;
}

.chart-container {
  height: 450px;
  padding-bottom: 10px;
}

/* 表格样式 */
.table-section {
  margin-bottom: 20px;
}

.table-card {
  border: none;
  border-radius: 12px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  flex-wrap: wrap;
  gap: 10px;
}

.table-pagination {
  margin-top: 20px;
  text-align: center;
}

/* 详情对话框样式 */
.detail-content {
  max-height: 600px;
  overflow-y: auto;
}

.mini-charts {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  margin-top: 15px;
}

.mini-chart {
  height: 120px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 10px;
}

/* 连接状态指示器 */
.connection-status {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 8px 15px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  font-weight: 500;
  z-index: 1000;
  transition: all 0.3s ease;
}

.connection-status.connected {
  background: #f0f9ff;
  color: #67c23a;
  border: 1px solid #b3e19d;
}

.connection-status.disconnected {
  background: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fbc4c4;
}

.connection-status.error {
  background: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #f5dab1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .realtime {
    padding: 10px;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
  
  .page-header p {
    font-size: 14px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .chart-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .table-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .gauge-container {
    height: 150px;
  }
  
  .chart-container {
    height: 300px;
  }
  
  .connection-status {
    bottom: 10px;
    right: 10px;
    font-size: 11px;
    padding: 6px 12px;
  }
}

@media (max-width: 480px) {
  .mini-charts {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .mini-chart {
    height: 100px;
  }
}
</style>